package cn.farm.farm.Controller.OrdinaryController;

import cn.farm.farm.Aop.IsLogin;
import cn.farm.farm.Config.Exception.OnlyOneImageException;
import cn.farm.farm.Entity.Ordinary.Image;
import cn.farm.farm.Entity.Ordinary.MatchImage;
import cn.farm.farm.Entity.Ordinary.Question;
import cn.farm.farm.Entity.Ordinary.QuestionWithImage;
import cn.farm.farm.MessageModel.Common;
import cn.farm.farm.MessageModel.PageHelperMessage;
import cn.farm.farm.MessageModel.StringCommon;
import cn.farm.farm.Service.OridinaryService.ImageService;
import cn.farm.farm.Service.OridinaryService.MatchImageService;
import cn.farm.farm.Service.OridinaryService.QuestionService;
import cn.farm.farm.Util.ImageUtil;
import cn.farm.farm.Util.QuestionWithImageHelper;
import cn.farm.farm.Util.UserUtil;
import cn.farm.farm.Util.file.OssUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/farm/ordinary")
public class QuestionController {

    @Autowired
    QuestionService questionService;

    @Autowired
    ImageService imageService;

    @Autowired
    MatchImageService matchImageService;

    @Autowired
    ImageUtil<Question> imageUtil;

    @GetMapping("quest/selectCount")
    public Common selectCount(){
        return new StringCommon(200,"ok",questionService.selectCount()+"");
    }

    @GetMapping("quest/selectByKey")
    public Common selectByKey(String key ,@RequestParam(value = "page",required = false,defaultValue = "1") int page,
                                          @RequestParam(value = "pageSize",required = false,defaultValue = "4")int pageSize){
        PageInfo<Question> info;
        PageHelper.startPage(page,pageSize);
        List<QuestionWithImage> questionWithImages = QuestionWithImageHelper.addImageID(questionService.selectBykey(key), matchImageService, imageService);
        info = new PageInfo(questionWithImages);
        if (info.getTotal()%pageSize!=0)
            info.setEndRow(info.getEndRow()+1);
        return new PageHelperMessage(200,"ok",info);
    }

    //查询本人的咨询 咨询image不为空
    @IsLogin
    @GetMapping(value = "quest/select")
    public Common select(HttpSession session, @RequestParam(value = "page",required = false,defaultValue = "1") int page,
                         @RequestParam(value = "pageSize",required = false,defaultValue = "2")int pageSize) {
        int userID = UserUtil.getUserID(session);
        List<QuestionWithImage> questionWithImages ;
        PageInfo<Question> info;
        try {
            PageHelper.startPage(page,pageSize);
            questionWithImages = questionService.selectByUserID(userID);
            questionWithImages = QuestionWithImageHelper.addImageID(questionWithImages,matchImageService,imageService);
            info = new PageInfo(questionWithImages);
            if (info.getTotal()%pageSize!=0)
                info.setEndRow(info.getEndRow()+1);

        } catch (Exception e) {
            e.printStackTrace();
            return new Common(500, "server error");
        }
        return new PageHelperMessage(200,"ok",info);
    }

    //查询所有咨询
    @GetMapping(value = "quest/selectAll")
    public Common selectAll(@RequestParam(value = "page",required = false,defaultValue = "1") int page,
                                @RequestParam(value = "pageSize",required = false,defaultValue = "2")int pageSize) {
        List<QuestionWithImage> questionWithImages;
        PageInfo<Question> info;
        try {
            PageHelper.startPage(page,pageSize);
            questionWithImages = questionService.selectAll();
            questionWithImages = QuestionWithImageHelper.addImageID(questionWithImages,matchImageService,imageService);
            info = new PageInfo(questionWithImages);
            if (info.getTotal()%pageSize!=0)
                info.setEndRow(info.getEndRow()+1);

        } catch (Exception e) {
            e.printStackTrace();
            return new Common(500, "server error");
        }
        return new PageHelperMessage(200,"ok",info);
    }


    //加入咨询
    @IsLogin
    @PostMapping(value = "quest/insert")
    public Common insert(HttpSession session ,String title , String content , String domain ,MultipartFile[] file1) {
        int userID = UserUtil.getUserID(session);
        Question question = new Question(domain,userID,title,content);
        //上传图片

        List<String> list = OssUtil.dealImage(file1);
        List<Image> images = new ArrayList<>();
        Image image ;
        for (String s : list) {
            image = new Image();
            image.setTime(new Date(System.currentTimeMillis()));
            image.setName(title);
            image.setFormat("png");
            image.setDescription(content);
            image.setImageFile(s);
            images.add(image);
        }

        //将图片对象插入数据库，并构建matchImage List集合
        List<MatchImage> matchImages = new ArrayList<>();
        List<Integer> lists = imageService.insertImageList(images);
        MatchImage matchImage;
        for (int i = 0; i < list.size(); i++) {
            matchImage = new MatchImage();
            matchImage.setImageID(lists.get(i));
            matchImage.setMatchinfo("咨询信息表的咨询图片");
            matchImages.add(matchImage);
        }
        //matchImages对象插入数据库 获得matchID 封装到question中 完成咨询添加
        try{
            int key =  matchImageService.insertList(matchImages);
            question.setTime(new Date(System.currentTimeMillis()));
            if(key != 0){
                question.setImage(key);
                questionService.insert(question);
            }else {
               return new Common(505,"图片上传失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            return new Common(500,"server error");
        }

        return new Common(200, "ok");
    }

    //咨询修改
    @PostMapping(value = "quest/update")
    @IsLogin
    public Common update(HttpSession session,String title, String content, @RequestParam("questID") int questID) {
        int userID = UserUtil.getUserID(session);
        //查询咨询是否存在，如果存在判断是否有权限修改
        Question targetQuestion;
        if ((targetQuestion = questionService.selectByQuestID(questID)) == null) {
            return new Common(404, "undefined");
        }
        if (userID != targetQuestion.getUserID()) {
            return new Common(401, "unauthorized");
        }

        Date nowtime = new Date(System.currentTimeMillis());
        try {
            questionService.updateQuestion(questID,title,content,nowtime);
        } catch (Exception e) {
            e.printStackTrace();
            return new Common(500, "server error");
        }

        return new Common(200, "ok");
    }

    //添加图片
    @IsLogin
    @PostMapping(value = "quest/insertImage")
    public Common insertImage(HttpSession session,@RequestParam(required = false,value ="file") MultipartFile file,
                              @RequestParam("matchID") int matchID, @RequestParam(value = "questID")int questID){
        int userID = UserUtil.getUserID(session);
        Question question;
        if((question = questionService.selectByQuestID(questID)) == null){
            return new Common(404,"undefined");
        }
        if(file == null || matchID == 0 || questID == 0){
            return new Common(400,"invalid request");
        }
        if(userID != question.getUserID()){
            return new Common(401,"unauthorized");
        }
        String path;
        Image image;
        MatchImage matchImage;
        try {
            path = OssUtil.uploadImage(file);
            image = new Image();
            image.setImageFile(path);
            image.setDescription(question.getContent());
            image.setName(question.getTitle());
            image.setTime(new Date(System.currentTimeMillis()));
            imageService.insert(image);
            matchImage = new MatchImage();
            matchImage.setImageID(image.getImageID());
            matchImage.setMatchinfo("咨询信息表的咨询图片");
            matchImage.setMatchID(matchID);
            matchImageService.insertWithMatchID(matchImage);
        } catch (Exception e){
            return new Common(500,"server error");
        }

        return new Common(200,"ok");
    }

    //删除图片
    @IsLogin
    @GetMapping(value = "quest/deleteImage")
    public Common deleteImage(HttpSession session, @RequestParam("imageID") int imageID , @RequestParam("questID") int questID){
        int userID = UserUtil.getUserID(session);
        if(imageID == 0 || questID == 0 ){
            return new Common(400,"invalid request");
        }
        Question question;
        if((question = questionService.selectByQuestID(questID)) == null ){
            return new Common(404,"undefined");
        }
        if(userID != question.getUserID()){
            return new Common(400,"unauthorized");
        }
        //级联删除图片，必须保留一张图片确保matchID存在
        try {
            questionService.deleteImage(imageID,questID);
        } catch (OnlyOneImageException e) {
            return new Common(407,"there is a image at least ");
        }catch (Exception e){
            return new Common(500,"server error");
        }
        return new Common(200,"ok");
    }

    //咨询删除
    @GetMapping(value = "quest/delete")
    public Common delete(HttpSession session, int questID) {
        int userID = UserUtil.getUserID(session);
        Question question;
        if ((question = questionService.selectByQuestID(questID)) == null) {
            return new Common(404, "undefined");
        }
        if (userID != question.getUserID()) {
            return new Common(400, "unauthorized");
        }
        try {
            questionService.deleteQuestion(questID);
        } catch (Exception e) {
            e.printStackTrace();
            return new Common(500, "server error");
        }
        return new Common(200, "ok");
    }

}
